﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThaiHoa.Win.QLSX.Entity;
using ThaiHoa.Win.QLSX.SanXuat.UTI;
using ThaiHoa.Win.QLSX.DAL;

namespace ThaiHoa.Win.QLSX.SanXuat.UI
{
    public partial class frmDoiSanXuatDetail : Form
    {
        #region Fields
        private KhoDBContext db;
        private BindingSource DoiSanXuatBS;
        public Guid Id;
        Access acs;
        public event EventHandler DBChanged;
        #endregion
        #region Constructor
        public frmDoiSanXuatDetail()
        {
            InitializeComponent();
        }
        #endregion
        #region Functions
        private void KhoiTao()
        {
            acs = new Access();
            db = new KhoDBContext();
            DoiSanXuatBS = new BindingSource();
            db.DoiSanXuat.Include("DayChuyen").Include("DanhSachThanhVien.LoaiCongNhan").Where(m => m.TrangThai).Load();
            DoiSanXuatBS.DataSource = db.DoiSanXuat.Local.ToBindingList();
            //Binding cho binding navigator
            //Binding cho combo
            List<DayChuyen> listDayChuyen;
            listDayChuyen = db.DayChuyen.Where(l => l.TrangThai).ToList();
            cbDayChuyen.DataSource = listDayChuyen;//set datasource cho combo
            cbDayChuyen.DataBindings.Clear();
            cbDayChuyen.DataBindings.Add("SelectedItem", DoiSanXuatBS, "DayChuyen", true);//binding
            //Binding cho textbox
            txtTen.DataBindings.Clear();
            txtTen.DataBindings.Add("Text", DoiSanXuatBS, "TenDonVi");
            txtMoTa.DataBindings.Clear();
            txtMoTa.DataBindings.Add("Text", DoiSanXuatBS, "MoTa");
            //Binding cho gridview
            dgvThanhVien.DataSource = DoiSanXuatBS;
            dgvThanhVien.DataMember = "DanhSachThanhVien";
            CustomerGridView();
            //Xử lý 2 trường hợp cụ thế :
            //Thêm mới và xem chi tiết
            if (Id != Guid.Empty)// Truong hop xem chi tiet
            {
                //Tìm vị trí của object có Id tương ứng
                int pos = -1;
                //pos = DoiSanXuatBS.Find("MaMatHang","dfi");
                DoiSanXuat item = db.DoiSanXuat.FirstOrDefault(m => m.Id.Equals(Id));
                if (item == null) return;
                pos = DoiSanXuatBS.List.IndexOf(item);
                if (pos < 0)
                    return;
                DoiSanXuatBS.Position = pos;
                this.Text = txtTen.Text;
            }
            else // Truong hop them moi
            {
                DoiSanXuatBS.AddNew();
                this.Text = "New Item";
            }
        }
        private void ReloadData()
        {
            if (db != null)
                db.Dispose();
            KhoiTao();
        }
        private void CustomerGridView()
        {
            //Ẩn toàn bộ columns
            foreach (DataGridViewColumn item in dgvThanhVien.Columns)
            {
                item.Visible = false;
            }
            //Tùy chỉnh lại
            //Không cho edit
            dgvThanhVien.ReadOnly = true;
            //Không cho thêm mới
            dgvThanhVien.AllowUserToAddRows = false;
            //Ẩn row header
            dgvThanhVien.RowHeadersVisible = false;
            //Tên
            var c = dgvThanhVien.Columns["HoVaTen"];
            c.Visible = true;
            c.Width = 200;
            c.DisplayIndex = 1;
            
            //Chức vụ
            c = dgvThanhVien.Columns["LoaiCongNhan"];
            c.Visible = true;
            c.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            c.DisplayIndex = 2;

        }
        /// <summary>
        /// Kiểm tra hợp lệ dữ liệu
        /// True: hợp lệ
        /// False :chưa hợp lệ
        /// </summary>
        /// <returns></returns>
        private bool KiemTraHopLeDuLieu()
        {
            bool result = true;
            errP.Clear();
            //Kiểm tra dây chuyền
            if (cbDayChuyen.SelectedItem == null)
            {
                errP.SetError(cbDayChuyen, "Dây chuyền không được rỗng");
                result = false;
            }
            
            if (txtTen.Text == "")
            {
                errP.SetError(txtTen, "Tên không được rỗng");
                result = false;
            }
            return result;
        }
        private int LuuLai()
        {
            DoiSanXuatBS.EndEdit();
            if (!KiemTraHopLeDuLieu()) return -1;
            if (MessageBox.Show("Lưu thay đổi ?", "Lưu Lại", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                int result = db.SaveChanges();
                if (DBChanged != null)
                {
                    DBChanged(this, EventArgs.Empty);
                }
                return result;
            }
            else
                return 0;
        }
        private void Cancel()
        {
            if (MessageBox.Show("Hủy thay đổi ?", "Lưu Lại", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                DoiSanXuatBS.CancelEdit();
                DoiSanXuatBS.ResetCurrentItem();
            }
        }
        private void Xoa()
        {
            if (Id == Guid.Empty)
            {
                this.Close();
                return;
            }
            if (Common.ShowMessengerConfirmDelete() == DialogResult.Yes)
            {
                DoiSanXuatBS.RemoveCurrent();
                db.SaveChanges();
                {
                    DBChanged(this, EventArgs.Empty);
                }
                this.Close();
            }
        }
        #endregion


        #region Events
        private void frmDoiSanXuatDetail_Load(object sender, EventArgs e)
        {
            KhoiTao();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            int result = LuuLai();
            if (result >= 0) this.Close();
        }
        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Cancel();
        }
        private void txtTen_TextChanged(object sender, EventArgs e)
        {
            this.Text = txtTen.Text;
        }
        private void btnAddNew_Click(object sender, EventArgs e)
        {
            acs.ShowFormDoiSanXuatDetail(Guid.Empty);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Xoa();
        }
        private void btn_ThanhVien_AddNew_Click(object sender, EventArgs e)
        {
            frmCongNhanSelectView _frmCongNhanSelectView = new frmCongNhanSelectView();
            _frmCongNhanSelectView.SelectedCongNhan += new EventHandler<SelectCongNhanEventArgs>(_frmCongNhanSelectView_SelectedCongNhan);
            _frmCongNhanSelectView.ShowDialog();
        }

        void _frmCongNhanSelectView_SelectedCongNhan(object sender, SelectCongNhanEventArgs e)
        {
            if (((DoiSanXuat)DoiSanXuatBS.Current).DanhSachThanhVien == null) return;
            List<CongNhan> listCongnhan = ((DoiSanXuat)DoiSanXuatBS.Current).DanhSachThanhVien;
            if (listCongnhan.Any(l => l.Id.Equals(e.CongNhan.Id)))// đã có công nhân này trong list
                return;//
            CongNhan item = db.CongNhan.Include("LoaiCongNhan").FirstOrDefault(c => c.Id.Equals(e.CongNhan.Id));
            if (item == null) return;
            
            ((DoiSanXuat)DoiSanXuatBS.Current).DanhSachThanhVien.Add(item);
            //Load lại gridview
            dgvThanhVien.DataSource = null;
            dgvThanhVien.DataSource = DoiSanXuatBS;
            dgvThanhVien.DataMember = "DanhSachThanhVien";
            CustomerGridView();
        }

        private void btn_ThanhVien_Delete_Click(object sender, EventArgs e)
        {
            if ((Guid)dgvThanhVien.CurrentRow.Cells["Id"].Value == null) return;
            Guid Id = (Guid)dgvThanhVien.CurrentRow.Cells["Id"].Value;
            if (Id == null || Id == Guid.Empty) return;
            CongNhan item = db.CongNhan.Include("LoaiCongNhan").FirstOrDefault(c => c.Id.Equals(Id));
            if (item == null) return;
            if (((DoiSanXuat)DoiSanXuatBS.Current).DanhSachThanhVien == null) return;
            ((DoiSanXuat)DoiSanXuatBS.Current).DanhSachThanhVien.Remove(item);
            //Load lại gridview
            dgvThanhVien.DataSource = null;
            dgvThanhVien.DataSource = DoiSanXuatBS;
            dgvThanhVien.DataMember = "DanhSachThanhVien";
            CustomerGridView();
        }

        private void btn_ThanhVien_Infomation_Click(object sender, EventArgs e)
        {
            if ((Guid)dgvThanhVien.CurrentRow.Cells["Id"].Value == null) return;
            Guid Id = (Guid)dgvThanhVien.CurrentRow.Cells["Id"].Value;
            if (Id == null || Id == Guid.Empty) return;
            //CongNhan item = db.CongNhan.Include("LoaiCongNhan").FirstOrDefault(c => c.Id.Equals(Id));
            //if (item == null) return;
            //Hiển thị form
            frmCongNhanDetail _frmCongNhanDetail = new frmCongNhanDetail();
            _frmCongNhanDetail.DBChanged += new EventHandler(_frmCongNhanDetail_DBChanged);
            acs.ShowFormCongNhanDetail(_frmCongNhanDetail, Id);
        }
        private void dgvThanhVien_DoubleClick(object sender, EventArgs e)
        {
            if ((Guid)dgvThanhVien.CurrentRow.Cells["Id"].Value == null) return;
            Guid Id = (Guid)dgvThanhVien.CurrentRow.Cells["Id"].Value;
            if (Id == null || Id == Guid.Empty) return;
            //CongNhan item = db.CongNhan.Include("LoaiCongNhan").FirstOrDefault(c => c.Id.Equals(Id));
            //if (item == null) return;
            //Hiển thị form
            frmCongNhanDetail _frmCongNhanDetail = new frmCongNhanDetail();
            _frmCongNhanDetail.DBChanged += new EventHandler(_frmCongNhanDetail_DBChanged);
            acs.ShowFormCongNhanDetail(_frmCongNhanDetail, Id);
        }
        void _frmCongNhanDetail_DBChanged(object sender, EventArgs e)
        {
            ReloadData();
        }
        #endregion

        

        









    }
}
